package com.ybear.ybcomponent.base.adapter.layoutcache

import android.util.SparseArray
import android.view.View
import java.lang.ref.SoftReference
import java.util.LinkedList

/**
 * @Author MiWi
 * @Date 2024年1月24日
 * @Description 布局优化-缓存池
 */
class ViewCache {
    private val mViewPools = SparseArray<LinkedList<SoftReference<View?>>>()
    private fun getViewPool(layoutId: Int): LinkedList<SoftReference<View?>> {
        var views = mViewPools[layoutId]
        if (views == null) {
            views = LinkedList()
            mViewPools.put(layoutId, views)
        }
        return views
    }

    fun getViewPoolAvailableCount(layoutId: Int): Int {
        val views = getViewPool(layoutId)
        val it = views.iterator()
        var count = 0
        while (it.hasNext()) {
            if (it.next().get() != null) {
                count++
            } else {
                it.remove()
            }
        }
        return count
    }

    fun putView(layoutId: Int, view: View?) {
        if (view == null) {
            return
        }
        getViewPool(layoutId).offer(SoftReference(view))
    }

    fun getView(layoutId: Int): View? {
        return getViewFromPool(getViewPool(layoutId))
    }

    private fun getViewFromPool(views: LinkedList<SoftReference<View?>>): View? {
        return if (views.isEmpty()) {
            null
        } else views.pop().get() ?: return getViewFromPool(views)
    }
}